package com.wzq.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import sun.misc.BASE64Decoder;

public class UploadPicUtil {
	private static final Logger logger = LogManager.getLogger(UploadPicUtil.class);
	public static void uploadPic(String picFileStr,String pic,String picturePath){
		BASE64Decoder decoder = new BASE64Decoder(); 
    	//Base64解码  
    	byte[] bfile = null ;
    	try {
            bfile = decoder.decodeBuffer(picFileStr);
            for(int i=0;i<bfile.length;++i)  
            {  
                if(bfile[i]<0)  
                {//调整异常数据  
                    bfile[i]+=256;  
                }  
            }  
        }
        catch (IOException e5) {
            throw new ApiException(ResponseCode.ERR.getCode(),"error ---> Base64解码异常，上传图片失败！");
        }  
		
    	//String picturePath = "";
        FileOutputStream fos1 = null;  
        BufferedOutputStream bos1 = null;   
    	try{
        	File shareFilePath = new File(picturePath);//图片公共目录
            if(!shareFilePath.exists()){  
                shareFilePath.mkdirs();  
            }
            if(!shareFilePath.isDirectory())
            {
                throw new ApiException(ResponseCode.ERR.getCode(),"上传图片共享路径配置有误");
            }
            File file1 = new File(shareFilePath+File.separator+pic);
            
            if(file1 != null && shareFilePath.isDirectory()){
                fos1 = new FileOutputStream(file1);  
                bos1 = new BufferedOutputStream(fos1);
                bos1.write(bfile);  
            }
    	} catch (IOException e5) {
            throw new ApiException(ResponseCode.ERR.getCode(),"error ---> Base64解码异常，上传图片失败！");
        }finally{
            if (bos1 != null) {  
                try {  
                    bos1.close();  
                    logger.debug("<-------  图片保存到共享目录流关闭1 ->");
                } catch (IOException e1) {
                    logger.info("error ---> 文件流关闭失败！");
                    e1.printStackTrace();  
                }  
            }
            if (fos1 != null) {  
                try {  
                    fos1.close();  
                    logger.debug("<-------  图片保存到共享目录流关闭2 ->");
                } catch (IOException e3) {  
                    logger.info("error ---> 文件流关闭失败！");
                    e3.printStackTrace();  
                }  
            }
        }
	}
	
}
